package indi.caibo.service_edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import indi.caibo.service_edu.entity.EduCourseLearn;
import indi.caibo.service_edu.mapper.EduCourseLearnMapper;
import indi.caibo.service_edu.service.EduCourseLearnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import indi.caibo.service_edu.service.EduCourseService;
import indi.caibo.service_edu.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程收藏 服务实现类
 * </p>
 *
 * @author Bo Cai
 * @since 2021-12-25
 */
@Service
public class EduCourseLearnServiceImpl extends ServiceImpl<EduCourseLearnMapper, EduCourseLearn> implements EduCourseLearnService {
    @Autowired
    EduVideoService videoService;
    @Autowired
    EduCourseService courseService;

    @Override
    public void learn(String memberId, String courseId, String chapterId, String videoId) {
        EduCourseLearn courseLearn = baseMapper.selectOne(new QueryWrapper<EduCourseLearn>().eq("member_id", memberId).eq("course_id", courseId).eq("chapter_id", chapterId).eq("video_id", videoId));
        if (courseLearn == null) {
            courseLearn = new EduCourseLearn();
            courseLearn.setMemberId(memberId);
            courseLearn.setCourseId(courseId);
            courseLearn.setChapterId(chapterId);
            courseLearn.setVideoId(videoId);
            baseMapper.insert(courseLearn);
        }
    }

    @Override
    public List<Map<String, Object>> totalLearnProgress(String memberId) {
        /*1. 查出当前用户学过的所有课程Id*/
        List<String> learnedCourseIds = baseMapper.getLearnedCourseIdsByMemberId(memberId);
        /*2. 查出这个课程总共有多少video，在统计已经学习了多少个video*/
        Map<String, Object> map;
        List<Map<String, Object>> items = new ArrayList<>();
        for (String courseId : learnedCourseIds) {
            int total = videoService.getCountByCourseId(courseId);
            int learned = baseMapper.selectCount(new QueryWrapper<EduCourseLearn>().eq("member_id", memberId).eq("course_id", courseId));
            map = new HashMap<>();
            map.put("course", courseService.getById(courseId));
            map.put("total", total);
            map.put("learned", learned);
            items.add(map);
        }
        return items;
    }
}
